package com.chinda.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinda.common.page.RPage;
import com.chinda.common.utils.SecurityUtil;
import com.chinda.modules.sys.dao.SysUserDao;
import com.chinda.modules.sys.entity.SysUserEntity;
import com.chinda.modules.sys.qo.SysUserQO;
import com.chinda.modules.sys.service.SysUserRoleService;
import com.chinda.modules.sys.service.SysUserService;
import lombok.AllArgsConstructor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * 系统用户
 *
 * @author chinda
 * @date 2021-06-16 05:52:51
 */
@Service("sysUserService")
@Transactional(readOnly = true, rollbackFor = Exception.class)
@AllArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {

    private final SysUserRoleService sysUserRoleService;

    /**
     * 获取分页信息
     *
     * @param qo
     * @return
     */
    @Override
    public RPage page(SysUserQO qo) {
        return new RPage(page(qo.getPage(), qo.getQueryWrapper()));
    }

    /**
     * 保存用户和角色关系
     *
     * @param sysUser
     * @param roleIdList
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUserAndRole(SysUserEntity sysUser, List<Long> roleIdList) {

        // 加密
        String password = sysUser.getPassword();
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        sysUser.setPassword(bCryptPasswordEncoder.encode(password));
        this.save(sysUser);
        Long userId = sysUser.getUserId();
        // 保存用户和角色关系
        sysUserRoleService.saveUserRole(userId, roleIdList);
    }

    /**
     * 修改用户和角色关系
     *
     * @param sysUser
     * @param roleIdList
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void modifyUserAndRole(SysUserEntity sysUser, List<Long> roleIdList) {
        sysUser.setPassword(null);
        this.updateById(sysUser);
        Long userId = sysUser.getUserId();
        // 保存用户和角色关系
        sysUserRoleService.saveUserRole(userId, roleIdList);
    }

    /**
     * 修改密码
     *
     * @param password
     * @param newPassword
     * @return
     */
    @Override
    public boolean modifyPassword(String password, String newPassword) {
        SysUserEntity userEntity = new SysUserEntity();
        userEntity.setPassword(newPassword);
        Long userId = SecurityUtil.getUserId();
        return this.update(userEntity,
                new QueryWrapper<SysUserEntity>().eq("user_id", userId).eq("password", password));
    }
}